<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class BaseModel extends Model
{
    use SoftDeletes;

    /**
     * 时间戳格式
     *
     * @var string
     */
    protected $dateFormat = 'Y-m-d H:i:s';

    /**
     * 时间戳字段
     *
     * @var bool
     */
    public $timestamps = true;

    /**
     * 软删除字段
     *
     * @var array
     */
    protected $dates = ['deleted_at'];

    /**
     * 默认排序
     *
     * @var string
     */
    protected $defaultOrderBy = 'id';

    /**
     * 默认排序方向
     *
     * @var string
     */
    protected $defaultOrderDirection = 'desc';

    /**
     * Boot the model.
     *
     * @return void
     */
    protected static function boot()
    {
        parent::boot();

        // 默认排序
        static::addGlobalScope('order', function ($builder) {
            $instance = new static;
            $builder->orderBy(
                $instance->defaultOrderBy,
                $instance->defaultOrderDirection
            );
        });
    }

    /**
     * 序列化日期时间
     * 统一使用 Y-m-d H:i:s 格式，并转换为应用时区
     *
     * @param \DateTimeInterface $date
     * @return string
     */
    protected function serializeDate(\DateTimeInterface $date): string
    {
        $timezone = config('app.timezone', 'Asia/Shanghai');
        return \Carbon\Carbon::instance($date)
            ->setTimezone($timezone)
            ->format('Y-m-d H:i:s');
    }
}

